package com.coderman.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyukang
 * @version 1.0
 * @since 2020/11/11 20:22
 **/
@Configuration
public class SwaggerConfig {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).pathMapping("/")
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.coderman"))
			.paths(PathSelectors.any())
			.build()
			.apiInfo(new ApiInfoBuilder().build())
			.securitySchemes(securitySchemes())
			.securityContexts(securityContexts());
	}

	private List<ApiKey> securitySchemes() {
		ArrayList<ApiKey> apiKeyList = new ArrayList<>();
		apiKeyList.add(new ApiKey("JSON WEB TOKEN(秘钥)", "Authorization", "header"));
		return apiKeyList;
	}

	private List<SecurityContext> securityContexts() {
		List<SecurityContext> securityContexts = new ArrayList<>();
		securityContexts.add(SecurityContext.builder()
			.securityReferences(defaultAuth())
			.forPaths(PathSelectors.regex("^(?!auth).*$"))
			.build());
		return securityContexts;
	}

	List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		List<SecurityReference> securityReferences = new ArrayList<>();
		securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
		return securityReferences;
	}

}
